package sword_offer;

import java.util.Arrays;

/**
 * @author Synhard
 * @version 1.0
 * @Class sword_offer.Code30
 * @Description 输入一个矩阵，按照从外向里以顺时针的顺序依次打印出每一个数字。
 * 示例 1：
 *
 * 输入：matrix = [[1,2,3],[4,5,6],[7,8,9]]
 * 输出：[1,2,3,6,9,8,7,4,5]
 * 示例 2：
 *
 * 输入：matrix =[[1,2,3,4],[5,6,7,8],[9,10,11,12]]
 * 输出：[1,2,3,4,8,12,11,10,9,5,6,7]
 *
 * 限制：
 *
 * 0 <= matrix.length <= 100
 * 0 <= matrix[i].length <= 100
 * @tel 13001321080
 * @email 823436512@qq.com
 * @date 2021-03-17 15:46
 */
public class Code30 {
    public static void main(String[] args) {
        int[][] data = new int[][]{{1,2,3,4},{5,6,7,8},{9,10,11,12}};
        System.out.println(Arrays.toString(spiralOrder(data)));
    }
    public static int[] spiralOrder(int[][] matrix) {
        if (matrix.length == 0) {
            return new int[]{};
        }
        int[] res = new int[matrix.length * matrix[0].length]; // 创建结果矩阵
        int top = 0, left = 0, bottom = matrix.length - 1, right = matrix[0].length - 1; // 初始化四个边界值
        int counter = 0; // 创建结果矩阵的索引以便于赋值
        while (true) {
            for (int i = left; i <= right; i++) {
                res[counter++] = matrix[top][i]; // 从左向右赋值
            }
            if (++top > bottom) {
                break;
            }
            for (int i = top; i <= bottom; i++) {
                res[counter++] = matrix[i][right]; // 从上向下赋值
            }
            if (--right < left) {
                break;
            }
            for (int i = right; i >= left; i--) {
                res[counter++] = matrix[bottom][i]; // 从右向左赋值
            }
            if (--bottom < top) {
                break;
            }
            for (int i = bottom; i >= top; i--) {
                res[counter++] = matrix[i][left]; // 从下向上赋值
            }
            if (++left > right) {
                break;
            }
        }
        return res;
    }
}
/*
设置四个边界依次进行赋值即可
 */
